import tkinter as tk
import pyaudio
import wave
import threading
import tkinter.messagebox
import os


class MainPage:
    def __init__(self,master:tk.Tk):
        with open('cn_chapter.txt',mode='r',encoding='utf-8') as f:
            self.TextRead = f.read()
        self.root = master
        self.root.geometry('600x400')
        self.root.title('魔镜 V0.0.1')
        self.page = tk.Frame(self.root)
        self.page.pack()
        self.text = tk.Text(self.page, width=60, height=10,autoseparators=True)
        self.text.pack(pady=30)#每行的宽度为60，显示8行#竖直边距设为30
        self.text.insert(tk.INSERT,self.TextRead)
        self.text.tag_add('tag1','0.0')
        self.text.tag_config('tag1',lmargin1=20)
        
        tk.Button(self.page,text='开始录制',command=self.start).pack(side='left',padx=10)
        tk.Button(self.page,text='停止录制',command=self.stop).pack(side='left',padx=10)
        tk.Button(self.page,text='重新录制',command=self.restart).pack(side='left',padx=10)
        tk.Button(self.page,text='  确认  ',command=self.sure).pack(side='left',padx=10)
        self.lbStatus = tk.Label(self.root, text='Ready', anchor='w', fg='green')    #靠左显示绿色状态字
        self.lbStatus.place(x=250, y=250, width=200, height=20)
         #音频采样率
        self.fileName = 'cn_chapter.wav' #文件名
        self.allowRecording = False      #录音状态
        self.CHUNK_SIZE = 1024           #数据块大小
        self.CHANNELS = 1                #频道
        self.FORMAT = pyaudio.paInt16    #16位量化编码
        self.RATE = 16000                #44100采样率


    def record(self):
        p = pyaudio.PyAudio()
        #audio流对象
        stream = p.open(format=self.FORMAT,
                        channels=self.CHANNELS,
                        rate=self.RATE,
                        input=True,
                        frames_per_buffer=self.CHUNK_SIZE)
        
        if os.path.exists("cn_chapter.wav"):    #判断是否存在对应文件
            os.remove("cn_chapter.wav")         #删除以实现覆盖写人
        
        #音频文件对象
        wf = wave.open(self.fileName, 'wb')
        wf.setnchannels(self.CHANNELS)
        wf.setsampwidth(p.get_sample_size(self.FORMAT))
        wf.setframerate(self.RATE)

        # 读取数据写入文件
        while self.allowRecording:
            data = stream.read(self.CHUNK_SIZE)
            wf.writeframes(data)
        wf.close()
        stream.stop_stream()
        stream.close()
        p.terminate()
        self.fileName = None

        
    def start(self):
        self.allowRecording = True
        self.lbStatus['text'] = 'Recording...'
        threading.Thread(target=self.record).start()
     

    def stop(self):
        self.allowRecording = False
        self.lbStatus['text'] = 'Ready'
    
    def restart(self):
        self.stop()
        self.start()

    def sure(self):
        from JScore import JScore
        self.page.destroy()
        JScore().show(master=self.root)
        
    def closeWindow(self):
        if self.allowRecording:
            tkinter.messagebox.showerror('Recording', 'Please stop recording before close the window.')
            return
        root.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    MP=MainPage(root)
    root.protocol('WM_DELETE_WINDOW', MP.closeWindow)
    root.mainloop()
